<template>
  <div class="efficiency-band-timeslot">
    <!-- 下拉列表 -->
    <el-card class="content__left">
      <realtimemonito-menu :data="menus" v-model:menu-id="menuId" v-model:open-id="openId" @menu-click="commEvent.menuClick" />
    </el-card>
    <!-- 展示信息 -->
    <div class="content__right">
      <!-- 搜索 -->
      <el-card>
        <el-row :gutter="20" align="middle">
          <el-col :span="6">
            <div class="right-search">
              <div class="search__label">时间：</div>
              <div class="search__value">
                <el-date-picker
                  v-model="searchValue.dataTime"
                  type="month"
                  placeholder="请选择"
                  style="width: 100%"
                  :clearable="false"
                />
              </div>
            </div>
          </el-col>
          <el-col :span="18">
            <el-row justify="end">
              <el-button type="primary" icon="Search" @click="commEvent.getStats">搜索</el-button>
              <el-button icon="Refresh" @click="commEvent.onReset">重置</el-button>
            </el-row>
          </el-col>
        </el-row>
      </el-card>
      <!-- 卡片 -->
      <el-row :gutter="10" class="right-cards">
        <el-col v-for="(item, index) in stats" :key="index" :span="24 / stats.length">
          <el-card>
            <div class="card__header">
              <el-image :src="item.icon" class="header__icon" />
              <div class="header__text">{{ item.label }}</div>
            </div>
            <div class="card__footer">
              <span>耗电量/kWh</span>
              <span :style="{ color: item.color }">{{ item.value }}</span>
            </div>
            <div class="card__footer">
              <span>耗电占比</span>
              <span :style="{ color: item.color }">{{ item.valueRatio }}%</span>
            </div>
            <div class="card__footer">
              <span>用电费用/元</span>
              <span :style="{ color: item.color }">{{ item.cost }}</span>
            </div>
            <div class="card__footer">
              <span>费用占比</span>
              <span :style="{ color: item.color }">{{ item.costRatio }}%</span>
            </div>
          </el-card>
        </el-col>
      </el-row>
      <!-- 图表 -->
      <el-card class="mt-10">
        <div class="card__title">尖峰平谷配置-尖峰平谷电量图</div>
        <div v-if="electricValue.length" class="card__cahrts">
          <e-charts :option="electricValueOption" />
        </div>
        <el-empty v-else />
      </el-card>
      <el-card class="mt-10">
        <div class="card__title">尖峰平谷配置-尖峰平谷电费图</div>
        <div v-if="electricCost.length" class="card__cahrts">
          <e-charts :option="electricCostOption" />
        </div>
        <el-empty v-else />
      </el-card>
    </div>
  </div>
</template>

<script setup lang="ts">
import { computed, onMounted, ref } from "vue"
import RealtimemonitoMenu, { MenuType } from "./components/RealtimemonitoMenu.vue"
import ECharts from "@/components/ECharts/index.vue"
import { ECOption } from "@/components/ECharts/config"
import { electricVoltage, statItem } from "./enum"
import dayjs from "dayjs"
import { organTree } from "@/api/modules/system"
import { SystemSpace as SystemApi } from "@/api/interface/system"
import { peakPlatValleyTotal, peakPlatValleyCostStat } from "@/api/modules/efficiency"
import { SystemSpace } from "@/api/interface/efficiency"

// 参数
const openId = ref<number[]>([])
const menuId = ref<number>(-1)
const menus = ref<MenuType[]>([]) // 菜单树结构
// 搜索项
const searchValue = ref({
  dataTime: dayjs().format("YYYY-MM")
})
// 菜单项
const menuValue = ref({
  factoryId: undefined as undefined | number,
  lineId: undefined as undefined | number
})
// 统计项
const stats = ref<any[]>(statItem)
// 电量
const electricValue = ref<SystemSpace.PeakPlatValleyCostStat["valueList"]>([])
const electricValueOption = computed<ECOption>(() => {
  let _series1: any = {}
  let _series2: any = {}
  let _series3: any = {}
  if (electricVoltage?.series && Array.isArray(electricVoltage.series)) {
    _series1 = electricVoltage.series[0]
    _series2 = electricVoltage.series[1]
    _series3 = electricVoltage.series[2]
  }
  return {
    ...electricVoltage,
    yAxis: { ...electricVoltage.yAxis, name: `耗电量(${electricValue.value.length ? electricValue.value[0].unit : ""})` },
    xAxis: { ...electricVoltage.xAxis, data: electricValue.value.map(item => item.dataTime) },
    series: [
      { ..._series1, data: electricValue.value.map(item => item.peakValue) },
      { ..._series2, data: electricValue.value.map(item => item.flatValue) },
      { ..._series3, data: electricValue.value.map(item => item.valleyValue) }
    ]
  }
})
// 电费
const electricCost = ref<SystemSpace.PeakPlatValleyCostStat["costList"]>([])
const electricCostOption = computed<ECOption>(() => {
  let _series1: any = {}
  let _series2: any = {}
  let _series3: any = {}
  if (electricVoltage?.series && Array.isArray(electricVoltage.series)) {
    _series1 = electricVoltage.series[0]
    _series2 = electricVoltage.series[1]
    _series3 = electricVoltage.series[2]
  }
  return {
    ...electricVoltage,
    yAxis: { ...electricVoltage.yAxis, name: `电费(${electricCost.value.length ? electricCost.value[0].unit : ""})` },
    xAxis: { ...electricVoltage.xAxis, data: electricCost.value.map(item => item.dataTime) },
    series: [
      { ..._series1, data: electricCost.value.map(item => item.peakValue) },
      { ..._series2, data: electricCost.value.map(item => item.flatValue) },
      { ..._series3, data: electricCost.value.map(item => item.valleyValue) }
    ]
  }
})
// 事件
const commEvent = {
  // 获取菜单信息
  getMenus: async () => {
    const { data } = await organTree()
    menus.value = commEvent.formatMenu(data)
    if (data && data.length > 0) {
      const _id: number = data[0].id
      menuId.value = _id
      openId.value = [_id]
    }
    commEvent.getStats()
  },
  // 格式化菜单树
  formatMenu: (data: SystemApi.OrganTree[], pids?: number[]): any[] => {
    if (!data || data.length <= 0) return []
    return data.map(item => {
      let pidArr: number[] = []
      if (pids) {
        pidArr = [...pids, item.pid || 0]
      }
      return {
        id: item.id,
        text: item.organName,
        level: item.level,
        pid: item.id,
        pidArr,
        children: commEvent.formatMenu(item.childrenTree || [], pidArr)
      }
    })
  },
  // 菜单点击
  menuClick: (item: any) => {
    if (item.level === 1) {
      menuValue.value.factoryId = item.id
      menuValue.value.lineId = undefined
    } else if (item.level === 2) {
      menuValue.value.factoryId = item.pid
      menuValue.value.lineId = item.id
    } else {
      menuValue.value.factoryId = undefined
      menuValue.value.lineId = undefined
    }
    commEvent.getStats()
  },
  // 重置
  onReset: () => {
    searchValue.value.dataTime = dayjs().format("YYYY-MM")
  },
  // 获取统计信息
  getStats: async () => {
    const params: SystemSpace.PeakPlatValleyTotalQuery = {
      ...menuValue.value,
      timeType: 2,
      dataTime: dayjs(searchValue.value.dataTime).format("YYYYMM")
    }
    const { data } = await peakPlatValleyTotal(params)
    const _data: any[] = JSON.parse(JSON.stringify(statItem))
    if (data && data.length) {
      _data.forEach(item => {
        data.forEach(val => {
          const _type: number = val.type || 666
          if (item.type === _type) {
            item.value = val.value || 0
            item.valueRatio = val.valueRatio || 0
            item.cost = val.cost || 0
            item.costRatio = val.costRatio || 0
          }
        })
      })
    }
    stats.value = _data
    const { data: costData } = await peakPlatValleyCostStat(params)
    electricValue.value = costData.valueList.map(item => ({
      ...item,
      dataTime: item.dataTime.substring(item.dataTime.length - 2) + "日"
    }))
    electricCost.value = costData.costList.map(item => ({
      ...item,
      dataTime: item.dataTime.substring(item.dataTime.length - 2) + "日"
    }))
  }
}
onMounted(() => {
  commEvent.getMenus()
})
</script>

<style lang="scss" scoped>
.mt-10 {
  margin-top: 10px;
}
.my-10 {
  margin: 10px 0;
}
.w-full {
  width: 100%;
}
.efficiency-band-timeslot {
  display: flex;
  width: 100%;
  height: calc(100vh - 100px);
  .card__title {
    position: relative;
    box-sizing: border-box;
    display: flex;
    align-items: center;
    width: 100%;
    padding-left: 8px;
    font-size: 16px;
    font-weight: bold;
    &::before {
      position: absolute;
      left: 0;
      width: 3px;
      height: 75%;
      content: "";
      background-color: #1d4a9d;
      border-radius: 16px;
    }
  }
  .content__left {
    width: 200px;
    :deep(.el-card__body) {
      padding: 0;
    }
    height: 100%;
    overflow-y: auto;
    padding-right: 4px; /* 为滚动条留空间 */
    scroll-behavior: smooth;
    /* 滚动条宽度 */
    &::-webkit-scrollbar {
      width: 3px;
    }
  }
  .content__right {
    box-sizing: border-box;
    flex: 1;
    min-width: 0;
    padding: 0 10px;
    overflow-y: auto;
    .right-search {
      display: flex;
      align-items: center;
      width: 100%;
      .search__label {
        flex-shrink: 0;
        font-size: 13px;
      }
      .search__value {
        flex: 1;
      }
    }
    .right-cards {
      margin-top: 10px;
      .card__header {
        display: flex;
        gap: 10px;
        align-items: center;
        width: 100%;
        .header__icon {
          width: 35px;
          height: 35px;
        }
        .header__text {
          font-size: 14px;
          font-weight: bold;
        }
      }
      .card__footer {
        display: flex;
        align-items: center;
        justify-content: space-between;
        width: 100%;
        margin-top: 10px;
        font-size: 14px;
        font-weight: bold;
      }
    }
    .card__cahrts {
      width: 100%;
      height: 300px;
    }
  }
}
</style>
